goog.provide('mitel.sidebar_gadget');

goog.require('goog.dom');
goog.require('goog.dom.forms');
goog.require('goog.events');
goog.require('goog.style');
goog.require('goog.window');
goog.require('mitel.deployment');
goog.require('mitel.messaging');
goog.require('mitel.presto');
goog.require('mitel.request');
goog.require('mitel.sidebar_gadget.widget');
goog.require('mitel.socket');


/**
 * @define {boolean} Should Presto be compiled into gadget.
 */
mitel.sidebar_gadget.ENABLE_PRESTO = true;

var user_email, socket;
var viewer=
{
    email: "",
    full_name: ""
};


/**
 * @param {{email: string}} data Email address of logged in user
 */
//                   _       
//                  (_)      
//   _ __ ___   __ _ _ _ __  
//  | '_ ` _ \ / _` | | '_ \ 
//  | | | | | | (_| | | | | |
//  |_| |_| |_|\__,_|_|_| |_|
//                           
//  This is the main function
//                          
var main = function(data) {
  var email = data['email'];
  viewer.full_name = viewer.email = user_email = email;

  soy.renderElement(document.body, mitel.sidebar_gadget.widget.container);
  // Don't use these anymore
  goog.style.setStyle(auth, 'display', 'none');
  goog.style.setStyle(sidebar_mobile, 'display', 'none');

  socket = mitel.socket.connect(mitel.deployment.socket_server);

  var incoming_calls = goog.dom.getElement('incoming_calls');

  socket.on('connect', function() {
    socket.emit('nickname', {
      'nickname': email
    });

    // presto uses the web socket right away so only boot presto
    // after you know the websocket is good to go
    if (mitel.sidebar_gadget.ENABLE_PRESTO) {
      var presto = goog.dom.getElement('presto');
      mitel.presto.boot(presto);
    }
  });

  calls = {};
  notifications = {};

  var removeCall = function(call_id) {
    /*
    goog.dom.removeNode(calls[call_id]);
    delete calls[call_id];
    if (goog.dom.getChildren(incoming_calls).length == 0) {
      goog.style.setStyle(incoming_calls, 'display', 'none');
    }
    */

    var notify = notifications[call_id];
    if (notify) {
      notify.close();
      delete notifications[call_id];
    }
  };

  socket.on('anouncement', function(data) {
    var removeThisCall = function() {
      return removeCall(data['gmail_id']);
    }

    var openEmailContext = function() {
      goog.window.popup(
          'https://mail.google.com/mail/?#inbox/' + data['gmail_id']
      );
      removeThisCall();
      socket.emit('call_accepted', data['gmail_id']);
    }

    var confirm = function() {
      if ( (typeof window.webkitNotifications != 'undefined') &&
           (window.webkitNotifications.checkPermission() == 0) ){
          var note = window.webkitNotifications.createNotification(mitel.deployment.host+'images/icon.png', 'Click2call', 
                     'Click to open email from ' + data['caller']+' about ' + data['subject']);

          // Give the user 7 secodns to read the note then cancel it
          note.ondisplay = function(event) {setTimeout(function() {event.currentTarget.cancel();}, 7000);};
          note.onclick = function(event){goog.window.popup( 'https://mail.google.com/mail/?#inbox/' + data['gmail_id'] )};
          note.onclose = removeThisCall;
          note.show();

          notifications[data['gmail_id']] = note;
      } else {
        /*
        var call = soy.renderAsElement(mitel.sidebar_gadget.widget.call, {});
        calls[data['gmail_id']] = call;

        goog.events.listen(call, goog.events.EventType.CLICK, function(event) {
          event.preventDefault();
          openEmailContext();
        });

        goog.style.setStyle(incoming_calls, 'display', 'block');
        goog.dom.appendChild(incoming_calls, call);
        */

        var msg = 'Incoming call from "' + data['caller'] + '" about email with subject "' + data['subject'] + '". Do you want to open the related email?';
        var r = window.confirm(msg);
        if (r) {
          openEmailContext();
        }
      }
    }

    confirm();
  });

  socket.on('call_accepted', function(data) {
    removeCall(data['gmail_id']);
  });

  socket.on('call_completed', function(data) {
    removeCall(data['gmail_id']);
  });

  var channel = mitel.messaging.init();
  channel.registerService('cookie:sentMobile', recieveMobile);

  var isMobileCheckbox = goog.dom.getElement('sidebar_ismobile');
  goog.events.listen(isMobileCheckbox, 'change', function(event) {
    var isChecked = !!goog.dom.forms.getValue(isMobileCheckbox);
    mitel.messaging.setMobile(isChecked);
  });

  var beta, gamma;

  goog.events.listen(goog.dom.getElement('radio_in'), goog.events.EventType.CLICK, function(event){
    beta = gamma = false;
    mitel.sidebar_gadget.emit_presence(false);
  });
  goog.events.listen(goog.dom.getElement('radio_out'), goog.events.EventType.CLICK, function(event){
    beta = gamma = false;
    mitel.sidebar_gadget.emit_presence(true);
  });

  socket.on('is_mobile', function(data) {
    var isMobile = data['isMobile'];
    mitel.sidebar_gadget.recievePresence(isMobile);
  });

  goog.events.listen(window, 'deviceorientation', function(event) {
    var radio_val = goog.dom.forms.getValueByName(goog.dom.getElement('presence1'), 'In_Out');
    if (radio_val == 'away') return;

    var devEvent = event.getBrowserEvent();

    var b = devEvent['beta'];
    var g = devEvent['gamma'];

    if (!beta) beta = b;
    if (!gamma) gamma = g;

    var delta = (beta + gamma) - (b + g);

    if (delta > 25 || delta < -25) {
      mitel.sidebar_gadget.recievePresence(true);
      mitel.sidebar_gadget.emit_presence(true);
      
      if (mitel.sidebar_gadget.ENABLE_PRESTO) {
         mitel.presto.invokeUpdatePresence();
      }
    }
  });
};

mitel.sidebar_gadget.emit_presence = function(outOfOffice) {
  socket.emit('is_mobile', {
    'isMobile': outOfOffice
  });
};

mitel.sidebar_gadget.recievePresence = function(outOfOffice) {
  if (outOfOffice && outOfOffice != 'false') {
    goog.dom.forms.setValue(goog.dom.getElement('radio_in'), false);
    goog.dom.forms.setValue(goog.dom.getElement('radio_out'), true);
  } else {
    goog.dom.forms.setValue(goog.dom.getElement('radio_in'), true);
    goog.dom.forms.setValue(goog.dom.getElement('radio_out'), false);
  }
};

var recieveMobile = function(isMobile) {
  mitel.messaging.recieveMobile(isMobile);
  var isMobileCheckbox = goog.dom.getElement('sidebar_ismobile');

  var val;
  if (isMobile && isMobile != 'false') {
    val = 'on';
  }

  goog.dom.forms.setValue(isMobileCheckbox, val);

  /*
  socket.emit('is_mobile', {
    'nickname': user_email,
    'isMobile': isMobile
  });
  */
};

mitel.sidebar_gadget.recieveMobile = recieveMobile;

//       _                               _   _     
//      | |                   /\        | | | |    
//   ___| |__   _____      __/  \  _   _| |_| |__  
//  / __| '_ \ / _ \ \ /\ / / /\ \| | | | __| '_ \ 
//  \__ \ | | | (_) \ V  V / ____ \ |_| | |_| | | |
//  |___/_| |_|\___/ \_/\_/_/    \_\__,_|\__|_| |_|
//
//  Ask for oauth permission and set up the popup Permissions button
//  The user has to click on this Permissions button to grant notification
//  popup permission
                                                
var showAuth = function(response) {
  var popup = new gadgets.oauth.Popup(
      response.oauthApprovalUrl, 'height=500,width=500', 
      function() {    // on open, do nothing
      }, function() {
        boot();      // on close go back to boot()
      });

  var onClick = function(event) {
    // It's important that this 'if' block
    // comes first
    if (window.webkitNotifications && // 0 is PERMISSION_ALLOWED
        window.webkitNotifications.checkPermission() != 0) {
      window.webkitNotifications.requestPermission();
    }

    // OAuth popup to grant access
    popup.createOpenerOnClick()();
  }

  var auth = goog.dom.getElement('auth');
  var auth_button = goog.dom.getElement('auth_button');
  goog.events.listen(auth_button, goog.events.EventType.CLICK, onClick);

  goog.style.setStyle(auth, 'display', 'block');
};

//   _                 _   
//  | |               | |  
//  | |__   ___   ___ | |_ 
//  | '_ \ / _ \ / _ \| __|
//  | |_) | (_) | (_) | |_ 
//  |_.__/ \___/ \___/ \__|
// 
// Render and obtain permissions (OAuth and permission for popup)
//
var boot = function() {
  goog.dom.removeChildren(document.body);
  soy.renderElement(document.body, mitel.sidebar_gadget.widget.container);

  url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json';
  mitel.request.makeRequest(url, function(response) {
    main(response.data);  // on success
  }, showAuth);  // on failure
};

//    _____ _             _     _    _               _ 
//   / ____| |           | |   | |  | |             | |
//  | (___ | |_ __ _ _ __| |_  | |__| | ___ _ __ ___| |
//   \___ \| __/ _` | '__| __| |  __  |/ _ \ '__/ _ \ |
//   ____) | || (_| | |  | |_  | |  | |  __/ | |  __/_|
//  |_____/ \__\__,_|_|   \__| |_|  |_|\___|_|  \___(_)
//                                                     
gadgets.util.registerOnLoadHandler(boot);
